package com.spbdx.common.utils.sms;

import com.alibaba.fastjson2.JSONObject;
import com.spbdx.common.exception.ServiceException;
import com.spbdx.common.utils.http.HttpUtils;
import com.spbdx.common.utils.sms.pojo.SendSmsEntity;
import com.spbdx.common.utils.sms.support.SmsConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * Description TODO
 *
 * @author chenwei
 * @version 1.0
 * @date 2023/1/13 14:22
 */
@Component
public class SmsUtil {

    @Value("${sms.appKey}")
    private String appKey;

    @Value("${sms.appSecret}")
    private String appSecret;

    private static final Logger log = LoggerFactory.getLogger(SmsUtil.class);

    /**
     * 短信发送
     *
     * @param mobiles
     * @param content
     * @param reportUrl
     */
    public void send(List<String> mobiles, String content, String reportUrl) {
        //1. 构建数据包对象
        SendSmsEntity sendEntity = SendSmsEntity.buildSendEntity(mobiles, appKey, appSecret, content, reportUrl);
/*        //2. 转化对象为json字符串数据
        String data = JSONObject.toJSONString(sendEntity);
        long t1 = System.currentTimeMillis();
        //3. 字符串url编码，防止特殊字符被客户端强行改变，譬如+会被浏览器或者其他客户端变更为空格
        String encodeData = URLEncoder.encode(data, "UTF-8");*/
        //4. 发送
        String resp = HttpUtils.sendPostJson(SmsConstants.SMS_SEND_URL, JSONObject.toJSONString(sendEntity), null);
        //5. 处理发送响应结果 resp.status==1时，
        JSONObject jsonObject = JSONObject.parseObject(resp);
        if (1 != jsonObject.getIntValue("status")) {
            if (log.isErrorEnabled()) {
                log.error(jsonObject.getString("message"));
            }
            throw new ServiceException("短信平台返回：" + jsonObject.getString("message"));
        }
    }

    public static void main(String[] args) {
        SmsUtil smsUtil = new SmsUtil();
        smsUtil.send(Arrays.asList("19123031978"), "【资产守护】验证码123456,请在3楼会议室等待。", "");
    }

}
